package service

import (
	"go-im/src/helper"
	"go-im/src/model"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

func ChatList(c *gin.Context) {
	roomIdentity := c.Query("room_identity")
	if roomIdentity == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "params room_identity error",
		})
		return
	}

	uc := c.MustGet("user_claims").(*helper.UserClaim)
	_, err := model.GetUserRoomByUserIdentityRoomIdentity(uc.Identity, roomIdentity)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "failed to access auth data: " + err.Error(),
		})
		return
	}

	pageIndex, _ := strconv.ParseInt(c.Query("page_index"), 10, 32)
	pageSize, _ := strconv.ParseInt(c.Query("page_size"), 10, 32)
	skip := (pageIndex - 1) * pageSize
	// find message list
	data, err := model.GetMessageListByRoomIdentity(roomIdentity, &pageSize, &skip)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "server internal error: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "load message list ok",
		"data": gin.H{
			"list": data,
		},
	})
}
